/*
@(#)SyncMessageProducer   2024-04-23
 
Copyright (c) 2011-2024 杭州湖畔网络技术有限公司 
保留所有权利 
本软件为杭州湖畔网络技术有限公司所有及包含机密信息，须遵守其相关许可证条款进行使用。
Copyright (c) 2011-2024 HUPUN Network Technology CO.,LTD.
All rights reserved.
This software is the confidential and proprietary information of HUPUN
Network Technology CO.,LTD("Confidential Information").  You shall not
disclose such Confidential Information and shall use it only in
accordance with the terms of the license agreement you entered into with HUPUN.
Website：http://www.hupun.com
*/
package org.obp.ons.normal.producer;

import com.alibaba.fastjson.JSONObject;
import com.aliyun.openservices.ons.api.Message;
import com.aliyun.openservices.ons.api.SendResult;
import com.aliyun.openservices.ons.api.bean.ProducerBean;
import com.aliyun.openservices.ons.api.exception.ONSClientException;
import lombok.extern.slf4j.Slf4j;
import org.obp.core.context.ObpContext;
import org.obp.ons.router.MqBizTags;
import org.obp.ons.consts.MqMessageType;
import org.obp.ons.topic.MqTopics;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;
import java.util.Date;

/**
 * @author: Jackey 2024/4/23
 */
@Slf4j
@Component
public final class MqMessageProducer {

    @Autowired
    private MqTopics mqTopics;
    @Autowired
    private ProducerBean producer;

    public void sendNormalMessage(JSONObject content, MqBizTags tags) {
        Message message = new Message();
        message.setTopic(mqTopics.getTopic());
        message.setKey(ObpContext.getTraceId());
        message.setTag(MqMessageType.NORMAL.name());

        content.put("_tag", tags.name());
        message.setBody(JSONObject.toJSONString(content).getBytes(StandardCharsets.UTF_8));
        try {
            SendResult sendResult = producer.send(message);
            assert sendResult != null;
            log.info("MQ发送成功, " + sendResult + " Text: {}", content);
        } catch (ONSClientException e) {
            log.error("MQ发送失败, Text: {}", content, e);
            // 出现异常意味着发送失败，为了避免消息丢失，建议缓存该消
        }
    }

    public void sendTimingMessage(JSONObject content, MqBizTags tags, Date deliverTime) {
        Message message = new Message();
        message.setTopic(mqTopics.getTopic_timing());
        message.setKey(ObpContext.getTraceId());
        message.setTag(MqMessageType.TIMING.name());

        content.put("_tag", tags.name());
        message.setBody(JSONObject.toJSONString(content).getBytes(StandardCharsets.UTF_8));
        message.setStartDeliverTime(deliverTime.getTime());
        try {
            SendResult sendResult = producer.send(message);
            assert sendResult != null;
            log.info("MQ发送成功, " + sendResult + " Text: {}, Time: {}", content, deliverTime);
        } catch (ONSClientException e) {
            log.error("MQ发送失败, Text: {}, Time: {}", content, deliverTime, e);
            // 出现异常意味着发送失败，为了避免消息丢失，建议缓存该消
        }
    }

}